package com.amithkoujalgi.framework.rest.services;


import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;

import com.amithkoujalgi.framework.rest.core.ApplicationContext;
import com.amithkoujalgi.framework.rest.domain.WebappResponse;

@Path("/app")
public class CoreSvc
{
	private static Logger logger = Logger.getLogger( CoreSvc.class );

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("/kill")
	public WebappResponse kill() throws Exception
	{
		int timeOut = 3;
		logger.info( "Kill operation requested." );
		new KillThread( timeOut ).start();
		WebappResponse r = new WebappResponse();
		r.setMessage( "Terminating app in " + timeOut + " seconds..." );
		return r;
	}

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("/config")
	public Map<Object, Object> config() throws Exception
	{
		Map<Object, Object> props = new HashMap<Object, Object>();
		for( Entry<Object, Object> e : com.amithkoujalgi.framework.rest.core.ApplicationContext.getInstance()
				.getConfig().entrySet() )
		{
			props.put( e.getKey(), e.getValue() );
		}
		return ApplicationContext.getInstance().getConfig();
	}


	class KillThread extends Thread
	{
		private Logger logger = Logger.getLogger( KillThread.class );
		private int timeOutSeconds;

		public KillThread (int shutdownTimeout)
		{
			this.timeOutSeconds = shutdownTimeout;
		}

		@Override
		public void run()
		{
			logger.info( "Terminating in " + (timeOutSeconds) + " seconds..." );
			try
			{
				Thread.sleep( timeOutSeconds * 1000 );
				ApplicationContext.getInstance().getComponentInit().killApp();
			}
			catch( Exception e )
			{
				e.printStackTrace();
			}
			System.exit( 1 );
		}
	}
}
